<?php

namespace App\Providers;

use App\Models\CustomerSessionInfo;
use App\User;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Gate;
use Illuminate\Support\ServiceProvider;

class AuthServiceProvider extends ServiceProvider
{
    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {

    }

    /**
     * Boot the authentication services for the application.
     *
     * @return void
     */
    public function boot2()
    {
        // Here you may define how you wish users to be authenticated for your Lumen
        // application. The callback which receives the incoming request instance
        // should return either a User instance or null. You're free to obtain
        // the User instance via an API token or any other method necessary.
        $this->app['auth']->viaRequest('api', function ($request) {
            if ($request->input('api_token')) {
                return User::where('api_token', $request->input('api_token'))->first();
            }
        });
    }
    public function boot()
    {
        //
        // Here you may define how you wish users to be authenticated for your Lumen
        // application. The callback which receives the incoming request instance
        // should return either a User instance or null. You're free to obtain
        // the User instance via an API token or any other method necessary.

        $this->app['auth']->viaRequest('api', function ($request)
        {

            $sKey = $request->header('X-WX-Skey');
            if ( ! $sKey )
            {
                $sKey = $request->header('X-WX-SKEY');
            }

            $fakeId = $request->header('X-WX-FakeId');
            if (env('API_FAKE_ID') && $fakeId)
            {
                app('log')->debug('use fake id: ' . $fakeId);
                $session = CustomerSessionInfo::query()->find($fakeId);
                return $session;
            }

            $session = CustomerSessionInfo::findBySkey($sKey);

            app('log')->debug("get host: " . $request->getHost() .' env ' . env('API_DEV_HOST', 'localhost'));

            if ( ! $session
                && env('APP_DEBUG') == true
                && $request->getHost() == env('API_DEV_HOST', 'localhost'))
            {
                $session = CustomerSessionInfo::query()->find(env('API_AUTH_USER'));

                app('log')->debug("session: " . env('API_AUTH_USER') . json_encode($session));
            }

            if ( ! $session )
            {
                app('log')->debug("can't find skey: " . $sKey);
                $data = DB::table('customer_session_infos')->where('skey', $sKey)->first();
                app('log')->debug("skey data info: " . var_export($data, true));
            }

            return $session;
        });
    }
}
